package cn.edu.scnu.semart.user.receiver;
import cn.edu.scnu.semart.mq.constant.MqConst;
import cn.edu.scnu.semart.user.service.UserFollowService;
import cn.edu.scnu.semart.vo.user.FollowMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Component
public class FollowReceiver {

    @Resource
    private UserFollowService userFollowService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_FOLLOW, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER_FOLLOW),
            key = MqConst.ROUTING_KEY_FOLLOW
    ))
    public void handleFollow(FollowMessage message, Message receivedMessage, Channel channel) throws IOException {
        try {
            userFollowService.follow(message.getFollowerId(), message.getFollowedId());
            long deliveryTag = receivedMessage.getMessageProperties().getDeliveryTag();
            channel.basicAck(deliveryTag, false);   // 确认消息
        } catch (Exception e) {
            log.error("Error processing follow message", e);
            long deliveryTag = receivedMessage.getMessageProperties().getDeliveryTag();
            channel.basicReject(deliveryTag, true);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_UNFOLLOW, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER_FOLLOW),
            key = MqConst.ROUTING_KEY_UNFOLLOW
    ))
    public void handleUnfollow(FollowMessage message, Message receivedMessage, Channel channel) throws IOException {
        try {
            userFollowService.unfollow(message.getFollowerId(), message.getFollowedId());
            long deliveryTag = receivedMessage.getMessageProperties().getDeliveryTag();
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("Error processing unfollow message", e);
            long deliveryTag = receivedMessage.getMessageProperties().getDeliveryTag();
            channel.basicReject(deliveryTag, true);
        }
    }
}